package io.renren.modules.pachong.service.impl;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.modules.pachong.Movie;
import io.renren.modules.pachong.MovieTag;
import io.renren.modules.pachong.dao.MovieDao;
import io.renren.modules.pachong.dao.MovieTagDao;
import io.renren.modules.pachong.service.MovieService;
import io.renren.modules.pachong.service.QiSiMovieService;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * 爬取骑士电影网数据
 *
 * @author Peter
 * @date 2018-8-13
 */
@Service("qiSiMovieService")
public class QiSiMovieServiceImpl extends ServiceImpl<MovieDao, Movie> implements QiSiMovieService {
    public static String URL = "http://www.7nmg.com/";
    @Autowired
    private MovieTagDao movieTagDao;
    @Autowired
    private MovieService movieService;


    private class MyThread implements Runnable {
        private int num;

        public MyThread(int num) {
            this.num = num;
        }

        @Override
        public void run() {
            addMoive(num);
        }
    }

    @Override
    public List<Movie> addMovie() {
        // 8个线程
        for (int i = 7; i >= 0; i--) {
            int num = i * 120;
            new Thread(new MyThread(num)).start();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public List<Movie> addMoive(int num) {
        Map<String, Map<String, Long>> tagMap = getTagMap();
        List<Movie> list = new ArrayList<>();
        // 分页
        for (int i = num + 120; i > num + 1; i--) {
            if (i > 909) {
                continue;
            }
//            System.out.println("第" + i + "页电影");
            Document doc = readData("http://www.7nmg.com/type/1/" + i + ".html");
            if (doc == null) {
                continue;
            }
            Elements lis = doc.getElementsByAttributeValue("class", "movie-item");
            int len = lis.size();
            if (lis.size() == 0) {
                continue;
            }
            // 处理每个movie
            for (int j = len - 1; j > 0; j--) {
//                System.out.print("第" + i + "_" + j + "个电影;");
                Element li = lis.get(j);
                Element a = li.getElementsByTag("a").get(0);
                String posterUrl = a.getElementsByTag("img").get(0).attr("src");
                String movieName = a.attr("title");
                String detailHtmlUrl = URL + a.attr("href");
                // 详情页
                Document detail_doc = readData(detailHtmlUrl);
                if (detail_doc == null) {
                    continue;
                }
                Element div = detail_doc.getElementsByAttributeValue("class", "online-button").get(0);
                if (div == null) {
                    continue;
                }
                Element aTag = div.getElementsByTag("a").first();
                String playDetailUrl = URL + aTag.attr("href");
                // 播放页
                Document play_doc = readData(playDetailUrl);
                if (play_doc == null) {
                    continue;
                }
                Element iframe = play_doc.getElementsByTag("iframe").first();
                if (iframe == null) {
                    continue;
                }
                String playUrl = iframe.attr("src");
                if (!isCanPlay(playUrl)) {
                    continue;
                }
                Movie m = new Movie();
                m.setName(movieName);
                m.setPlayUrl(playUrl);
                m.setPosterUrl(posterUrl);
                Elements trs = detail_doc.getElementsByTag("tr");
                if (trs != null) {
                    for (int k = 0; k < trs.size(); k++) {
                        Element td = trs.get(k).children().last();
                        // 导演
                        if(k == 0){
                            m.setDirector(td.text().split("/")[0]);
                        }else if(k == 1){// 主演，只保留第一个
                            String[] arr = td.text().split("/");
                            m.setActor(arr[0].trim());
                        }else if(k == 2) {// 类型
                            String typeStr = "";
                            Map<String, Long> map = tagMap.get("1");
                            // 多个类型
                            String text = td.text();
                            String[] arr = text.split("/");
                            String str = arr[0].trim();
                            if (map.containsKey(str)) {
                                Long id = map.get(str);
                                typeStr += id + ",";
                            }
                            int strLen = typeStr.length();
                            if (strLen > 0) {
                                m.setType(typeStr.substring(0, typeStr.length() - 1));
                            }
                        } else if (k == 3) {// 地区
                            Map<String, Long> map = tagMap.get("2");
                            String country = td.text().split("/")[0].split(" ")[0];
                            if (map.containsKey(country)) {
                                m.setCountry(map.get(country) + "");
                            }else{
                                m.setCountry("62");
                            }
                        }else if(k == 4){// 分辨率
                            m.setResolution(td.text());
                        }else if (k == 5) {
                            Element tr = trs.get(k);
                            Elements tds = tr.getElementsByTag("td");
                            String year = tds.last().text();
                            if (!StringUtils.isBlank(year)) {
                                int intYear = toInt(year);
                                if (intYear <= 0) {
                                    continue;
                                }
                                m.setYear(intYear);
                            }

                        }
                    }
                }//
                Element summary = detail_doc.getElementsByAttributeValue("class","summary").first();
                String str = summary.text();
                int strLen = str.length();
                m.setSummary(strLen > 900 ? summary.text().substring(0,900):str);
                list.add(m);
            }
        }
        movieService.insertBatch(list);
        System.out.print("===================================================================================================================");
        return list;
    }

    public Integer toInt(String str) {
        try {
            return Integer.valueOf(str.substring(0, 4));
        } catch (Exception e) {
            return 0;
        }
    }

    public Map<String, Long> getExistsMap(Long pid) {
        EntityWrapper<MovieTag> ew = new EntityWrapper<>();
        ew.eq("pid", pid);
        List<MovieTag> list = movieTagDao.selectList(ew);
        Map<String, Long> map = new HashMap<>();
        if (list != null && list.size() > 0) {
            for (MovieTag m : list) {
                map.put(m.getName(), m.getId());
            }
        }
        return map;
    }

    public void addMovieTag() {
        Map<String, Long> typeMap = getExistsMap(1L);
        Map<String, Long> countryMap = getExistsMap(2L);
        for (int i = 0; i < 8; i++) {
            new Thread(new MyTagThread(typeMap, countryMap, i * 120)).start();
        }
    }

    private class MyTagThread implements Runnable {
        private Map<String, Long> typeMap;
        private Map<String, Long> countryMap;
        private int num;

        public MyTagThread(Map<String, Long> typeMap, Map<String, Long> countryMap, int num) {
            this.typeMap = typeMap;
            this.countryMap = countryMap;
            this.num = num;
        }

        public void run() {
            addMovieTags(typeMap, countryMap, num);
        }

    }

    public void addMovieTags(Map<String, Long> typeMap, Map<String, Long> countryMap, int num) {
        for (int i = num + 1; i <= num + 120; i++) {
            System.out.println("第 " + i + "页");
            Document doc = readData("http://www.7nmg.com/type/1/" + i + ".html");
            if (doc == null) {
                continue;
            }
            Elements lis = doc.getElementsByAttributeValue("class", "movie-item");
            int len = lis.size();
            if (len == 0) {
                continue;
            }
            // 处理每个电影
            for (int j = 0; j < len; j++) {
                System.out.print("第" + j + "个电影");
                Element li = lis.get(j);
                Element a = li.getElementsByTag("a").get(0);
                String detailHtmlUrl = URL + a.attr("href");
                // 详情页
                Document detail_doc = readData(detailHtmlUrl);
                if (detail_doc == null) {
                    continue;
                }
                // 只导能播放的
                Element div = detail_doc.getElementsByAttributeValue("class", "online-button").get(0);
                if (div == null) {
                    continue;
                }
                Element aTag = div.getElementsByTag("a").first();
                String playDetailUrl = URL + aTag.attr("href");
                // 播放页
                Document play_doc = readData(playDetailUrl);
                if (play_doc == null) {
                    continue;
                }
                Element iframe = play_doc.getElementsByTag("iframe").first();
                if (iframe == null) {
                    continue;
                }
                String playUrl = iframe.attr("src");
                if (!isCanPlay(playUrl)) {
                    continue;
                }
                Elements trs = detail_doc.getElementsByTag("tr");
                if (trs != null) {//2.3
                    for (int k = 0; k < trs.size(); k++) {
                        if (k > 3) {
                            break;
                        }
                        // 类型
                        if (k == 2) {
                            Element tr = trs.get(k);
                            Element td = tr.getElementsByTag("td").last();
                            String val = td.text();
                            String[] arr = val.split("/");
                            String str = arr[0].trim();
                            if (!typeMap.containsKey(str)) {
                                MovieTag tag = new MovieTag();
                                tag.setPid(1L);
                                tag.setName(str);
                                movieTagDao.insert(tag);
                                typeMap.put(str, tag.getId());
                            }
                        } else if (k == 3) {// 地区
                            Element tr = trs.get(k);
                            Element td = tr.getElementsByTag("td").last();
                            String val = td.text();
                            String[] arr = val.split("/");
                            String str = arr[0].trim().split(" ")[0];
                            if (!countryMap.containsKey(str)) {
                                MovieTag tag = new MovieTag();
                                tag.setPid(2L);
                                tag.setName(str.split(" ")[0]);
                                movieTagDao.insert(tag);
                                countryMap.put(str, tag.getId());
                            }

                        }
                    }

                }
            }
        }
    }


    public Map<String, Map<String, Long>> getTagMap() {
        EntityWrapper<MovieTag> ew = new EntityWrapper<>();
        ew.eq("pid", 0);
        List<MovieTag> tagList = movieTagDao.selectList(ew);
        Map<String, Map<String, Long>> map = new HashMap<>();
        for (MovieTag t : tagList) {
            EntityWrapper<MovieTag> ews = new EntityWrapper<>();
            ew.eq("pid", t.getId());
            List<MovieTag> children = movieTagDao.selectList(ews);
            Map<String, Long> childMap = new HashMap<>();
            for (MovieTag tag : children) {
                childMap.put(tag.getName(), tag.getId());
            }
            map.put(t.getId() + "", childMap);
        }
        return map;
    }

    public Document readData(String url) {
        Document doc = null;
        try {
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return doc;
    }

    // 判断是否能播放
    private boolean isCanPlay(String urlStr) {
        try {
            Document doc = Jsoup.connect(urlStr).get();
            Element error = doc.getElementById("error");
            if(error != null){
                return false;
            }else{
                Elements imgs = doc.getElementsByTag("img");
                if(imgs != null ){
                    for(Element img : imgs){
                        String src = img.attr("src");
                        if(src.contains("404.")){
                            return  false;
                        }
                    }
                }else{
                    Elements qr= doc.getElementsByAttributeValue("class","PanBox");
                    if(qr != null){
                        return false;
                    }

                }
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

}
